package net.longjin.config;

import lombok.extern.slf4j.Slf4j;
import net.longjin.annotation.IgnoreAuth;
import net.longjin.enums.ResBizCode;
import net.longjin.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        IgnoreAuth ignoreAuthAnnotation;

        if (handler instanceof HandlerMethod) {
            ignoreAuthAnnotation = ((HandlerMethod)handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }

        // 如果有@IgnoreAuth注解，则不验证token
        if (ignoreAuthAnnotation != null) {
            return true;
        }
        // 从header中获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            log.info("token is empty, the requested url :" + request.getRequestURL());
            throw new BizException(ResBizCode.EMPTY_TOKEN_ERROR);
        }

      return true;
    }
}
